let Oled  =  require ('oled-i2c-bus')
import nowTime from './utils/nowTime'
import MyRedis from './api/REDIS'
import SYSTEM from './api/SYSTEM'
import Draw from './api/OLED'
import FAN from './api/FAN'
import RGB from './api/RGB'
import i2c from 'i2c-bus'
import axios from 'axios'
import DISK from './api/DISK'
const config = require('config')


// i2c设备地址
const Addr = 0x0d
// 实例化RGB灯/风扇/数据库实例
const rgb = new RGB(i2c, Addr)
const fan = new FAN(i2c, Addr)
const reids = new MyRedis()


// oled屏幕相关
const i2cBus = i2c.openSync(1)
const options = { widht: 128, height: 32, address: 0x3C }
const oled = new Oled(i2cBus, options)

// 获取默认设置
const isRGB = config.get('RGB') // RGB状态灯默认设置
const isFAN = config.get('FAN') // 风扇默认设置
const isREDIS = config.get('REDIS') // redis数据库默认设置
const isOLED = config.get('OLED') // OLED屏幕默认设置
const isServerJiang = config.get('SERVER_JIANG') // server酱默认设置
const isDISK = config.get('DISK') // 保持唤醒默认设置

// 设备状态
let statusRGB = isRGB
let statusFAN:boolean = false
let statusIP: string = ''

/**主程序结构 */
if (isREDIS.enable) reids.connect() // 链接数据库
console.log(nowTime(), '启动亚博智能风冷驱动')
// 主程序循环
setInterval(async () => {
  try {
      // 获取系统信息(CPU使用率 内存 硬盘 IP CPU温度)
      const system = await SYSTEM()
      // console.log(system)
    
      // 判断ip是否更新并是否使用server酱通知
      if (statusIP !== system.ip) {
        statusIP = system.ip as string
        console.log(nowTime(), 'ip已更新', system.ip)
        if (isServerJiang.enable) axios.get(`https://sctapi.ftqq.com/${isServerJiang.SendKey}.send?title=IP:${system.ip}`)
      }
    
      // 热更新设置
      const effect = isREDIS.enable? parseInt(await reids.hGet('RGB', 'effect') as string) : isRGB.effect
      const speed = isREDIS.enable? parseInt(await reids.hGet('RGB', 'speed') as string) : isRGB.speed
      const color = isREDIS.enable? parseInt(await reids.hGet('RGB', 'color') as string) : isRGB.color
    
      /* 设置RGB灯 (节流:无新设置则 不执行) */
      if (effect != statusRGB.effect || speed != statusRGB.speed || color != statusRGB.color) {
        rgb.SetupRGB(effect, speed, color)
        // 更新配置信息(合并对象)
        statusRGB = {effect, speed, color}
        // console.log(nowTime(), '更新灯模式');
      }
    
      /* 设置风扇开关 */
      if (system.temp >= isFAN.StartTemp && !statusFAN || system.temp > isFAN.MaxStartTemp) {
        fan.openFAN()
        statusFAN = true
        // console.log(nowTime(), '开启风扇', system.temp)
        // 温度低于设置温度 并且风扇是开的状态就关闭风扇
      } else if (system.temp < isFAN.StartTemp && statusFAN || system.temp < isFAN.MinStopTemp) {
        fan.closeFAN()
        statusFAN = false
        // console.log(nowTime(), '关闭风扇', system.temp)
      }
    
        /* OLED屏幕绘制 */
        if (isOLED.enable) Draw(oled, system)
    
        /* 保持唤醒硬盘 */
        if (isDISK.enable) DISK(isDISK.fileUrl)

  } catch (error) {
    console.log(nowTime(), error)
  }
  // if (isREDIS.enable) await reids.disconnect() // 断开数据库链接

}, 2000)


